<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MetasoCreator 功能演示</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }

        .nav-tabs {
            display: flex;
            background: #f8f9fa;
            border-bottom: 2px solid #e9ecef;
        }

        .nav-tab {
            flex: 1;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            border-bottom: 3px solid transparent;
        }

        .nav-tab:hover {
            background: #e9ecef;
        }

        .nav-tab.active {
            background: white;
            border-bottom-color: #4facfe;
            color: #4facfe;
            font-weight: bold;
        }

        .tab-content {
            display: none;
            padding: 30px;
        }

        .tab-content.active {
            display: block;
        }

        .function-card {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            border-left: 5px solid #4facfe;
        }

        .function-card h3 {
            color: #2c3e50;
            margin-bottom: 15px;
            font-size: 1.4em;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #495057;
        }

        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: #4facfe;
            box-shadow: 0 0 0 3px rgba(79, 172, 254, 0.1);
        }

        .btn {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s ease;
            margin-right: 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(79, 172, 254, 0.4);
        }

        .btn-secondary {
            background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
        }

        .btn-success {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }

        .btn-danger {
            background: linear-gradient(135deg, #dc3545 0%, #fd7e14 100%);
        }

        .response-area {
            background: #2d3748;
            color: #e2e8f0;
            padding: 20px;
            border-radius: 10px;
            margin-top: 20px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            max-height: 400px;
            overflow-y: auto;
            white-space: pre-wrap;
        }

        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-success {
            background: #28a745;
        }

        .status-error {
            background: #dc3545;
        }

        .status-loading {
            background: #ffc107;
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        .grid-2 {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .grid-3 {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 20px;
        }

        .alert {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid;
        }

        .alert-info {
            background: #d1ecf1;
            border-color: #17a2b8;
            color: #0c5460;
        }

        .alert-success {
            background: #d4edda;
            border-color: #28a745;
            color: #155724;
        }

        .alert-warning {
            background: #fff3cd;
            border-color: #ffc107;
            color: #856404;
        }

        .alert-danger {
            background: #f8d7da;
            border-color: #dc3545;
            color: #721c24;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #4facfe;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @media (max-width: 768px) {
            .grid-2, .grid-3 {
                grid-template-columns: 1fr;
            }
            
            .nav-tabs {
                flex-direction: column;
            }
            
            .container {
                margin: 10px;
                border-radius: 15px;
            }
        }

        /* 新增：网页读取结果的专用容器样式，避免绿色/红色背景遮挡内容 */
        .reader-area {
            background: #fff;
            color: #333;
            padding: 20px;
            border-radius: 10px;
            margin-top: 20px;
            border: 1px solid #e9ecef;
            font-size: 14px;
        }
        .reader-meta { color: #555; margin: 6px 0; }
        .reader-meta strong { color: #2c3e50; }
        .reader-pre {
            background: #fff;
            color: #1f2937;
            padding: 16px;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
            font-size: 15px;
            line-height: 1.8;
            white-space: pre-wrap;
            max-height: 560px;
            overflow-y: auto;
            margin-top: 10px;
        }
        .hidden { display: none !important; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 MetasoCreator 功能演示</h1>
            <p>体验智能搜索、内容管理等核心功能</p>
        </div>

        <div class="nav-tabs">
            <div class="nav-tab active" onclick="showTab('search')">🔍 智能搜索</div>
            <div class="nav-tab" onclick="showTab('reader')">📖 网页读取</div>
            <div class="nav-tab" onclick="showTab('qa')">🤖 智能问答</div>
            <div class="nav-tab hidden" onclick="showTab('content')">📝 内容管理</div>
            <div class="nav-tab" onclick="showTab('system')">⚙️ 系统监控</div>
        </div>

        <!-- 智能搜索标签页 -->
        <div id="search" class="tab-content active">
            <div class="alert alert-info">
                <strong>💡 提示：</strong> 智能搜索模块集成了秘塔AI搜索API，支持网页搜索、学术搜索等多种模式
            </div>

            <!-- 搜索功能 -->
            <div class="function-card">
                <h3>🔍 执行搜索</h3>
                <div class="grid-3">
                    <div class="form-group">
                        <label>搜索关键词 *</label>
                        <input type="text" id="searchQuery" class="form-control" placeholder="例如：人工智能" value="人工智能">
                    </div>
                    <div class="form-group">
                        <label>搜索范围（可多选）</label>
                        <div id="searchScope" class="checkbox-group" style="border: 1px solid #ddd; padding: 10px; border-radius: 4px; background-color: #f9f9f9;">
                            <div style="margin-bottom: 8px;">
                                <input type="checkbox" id="scope_webpage" value="webpage" checked>
                                <label for="scope_webpage" style="display: inline; margin-left: 5px; font-weight: normal;">网页搜索</label>
                            </div>
                            <div style="margin-bottom: 8px;">
                                <input type="checkbox" id="scope_scholar" value="scholar">
                                <label for="scope_scholar" style="display: inline; margin-left: 5px; font-weight: normal;">学术搜索</label>
                            </div>
                            <div style="margin-bottom: 8px;">
                                <input type="checkbox" id="scope_document" value="document">
                                <label for="scope_document" style="display: inline; margin-left: 5px; font-weight: normal;">文档搜索</label>
                            </div>
                            <div style="margin-bottom: 8px;">
                                <input type="checkbox" id="scope_podcast" value="podcast">
                                <label for="scope_podcast" style="display: inline; margin-left: 5px; font-weight: normal;">播客搜索</label>
                            </div>
                            <div style="margin-bottom: 8px;">
                                <input type="checkbox" id="scope_image" value="image">
                                <label for="scope_image" style="display: inline; margin-left: 5px; font-weight: normal;">图片搜索</label>
                            </div>
                            <div style="margin-bottom: 0;">
                                <input type="checkbox" id="scope_video" value="video">
                                <label for="scope_video" style="display: inline; margin-left: 5px; font-weight: normal;">视频搜索</label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>包含摘要</label>
                        <select id="includeSummary" class="form-control">
                            <option value="false">否</option>
                            <option value="true">是</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label>分页方式</label>
                    <div style="margin-bottom: 15px;">
                        <input type="radio" id="usePage" name="pagingType" value="page" checked onchange="togglePagingInputs()">
                        <label for="usePage" style="display: inline; margin-left: 5px; margin-right: 20px;">使用页码</label>
                        <input type="radio" id="useSize" name="pagingType" value="size" onchange="togglePagingInputs()">
                        <label for="useSize" style="display: inline; margin-left: 5px;">使用每页大小</label>
                    </div>
                </div>
                <div class="grid-2">
                    <div class="form-group" id="pageGroup">
                        <label>页码</label>
                        <input type="number" id="searchPage" class="form-control" value="1" min="1">
                    </div>
                    <div class="form-group" id="sizeGroup" style="display: none;">
                        <label>每页大小</label>
                        <input type="number" id="searchSize" class="form-control" value="10" min="1" max="50">
                    </div>
                </div>
                <button class="btn" onclick="executeSearch()">🚀 开始搜索</button>
                <div id="searchResponse" class="response-area" style="display: none;"></div>
            </div>

            <!-- 搜索建议 -->
            <div class="function-card">
                <h3>💡 搜索建议</h3>
                <div class="grid-2">
                    <div class="form-group">
                        <label>部分查询词</label>
                        <input type="text" id="suggestionQuery" class="form-control" placeholder="例如：人工" value="人工">
                    </div>
                    <div class="form-group">
                        <label>建议数量</label>
                        <input type="number" id="suggestionLimit" class="form-control" value="5" min="1" max="20">
                    </div>
                </div>
                <button class="btn" onclick="getSuggestions()">💡 获取建议</button>
                <div id="suggestionResponse" class="response-area" style="display: none;"></div>
            </div>

            <!-- 搜索历史 -->
            <div class="function-card">
                <h3>📚 搜索历史</h3>
                <div class="grid-2">
                    <div class="form-group">
                        <label>用户ID *</label>
                        <input type="text" id="historyUserId" class="form-control" placeholder="输入用户ID" value="demo_user">
                    </div>
                    <div class="form-group">
                        <label>历史记录数量</label>
                        <input type="number" id="historyLimit" class="form-control" value="20" min="1" max="100">
                    </div>
                </div>
                <button class="btn" onclick="getSearchHistory()">📚 获取历史</button>
                <button class="btn btn-danger" onclick="clearSearchHistory()">🗑️ 清除历史</button>
                <div id="historyResponse" class="response-area" style="display: none;"></div>
            </div>

            <!-- 搜索测试 -->
            <div class="function-card">
                <h3>🧪 搜索API测试</h3>
                <p>测试搜索API的连接状态和基本功能</p>
                <button class="btn" onclick="testSearchAPI()">🧪 测试连接</button>
                <div id="testResponse" class="response-area" style="display: none;"></div>
            </div>
        </div>

        <!-- 网页读取标签页 -->
        <div id="reader" class="tab-content">
            <div class="alert alert-info">
                <strong>💡 提示：</strong> 网页读取模块支持获取指定URL的网页内容，并以Markdown格式返回
            </div>

            <!-- 网页读取功能 -->
            <div class="function-card">
                <h3>📖 读取网页内容</h3>
                <div class="form-group">
                    <label>网页URL *</label>
                    <input type="text" id="readerUrl" class="form-control" placeholder="例如：https://www.example.com" value="https://www.baidu.com">
                </div>
                <button class="btn" onclick="readWebpage()">📖 读取网页</button>
                <div id="readerResponse" class="response-area" style="display: none;"></div>
            </div>

            <!-- 网页读取测试 -->
            <div class="function-card">
                <h3>🧪 网页读取API测试</h3>
                <p>测试网页读取API的连接状态和基本功能</p>
                <button class="btn" onclick="testReaderAPI()">🧪 测试连接</button>
                <div id="readerTestResponse" class="response-area" style="display: none;"></div>
            </div>
        </div>

        <!-- 智能问答标签页 -->
        <div id="qa" class="tab-content">
            <div class="alert alert-info">
                <strong>💡 提示：</strong> 智能问答模块基于秘塔AI，支持多轮对话和智能回答
            </div>

            <!-- 问答功能 -->
            <div class="function-card">
                <h3>🤖 智能问答</h3>
                <div class="grid-2">
                    <div class="form-group">
                        <label>搜索范围</label>
                        <select id="qaScope" class="form-control">
                            <option value="webpage">网页搜索</option>
                            <option value="scholar">学术搜索</option>
                            <option value="document">文档搜索</option>
                            <option value="podcast">播客搜索</option>
                            <option value="image">图片搜索</option>
                            <option value="video">视频搜索</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>模型选择</label>
                        <select id="qaModel" class="form-control">
                            <option value="fast_thinking">快速思考</option>
                            <option value="deep_thinking">深度思考</option>
                            <option value="gpt-4">GPT-4</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label>对话历史</label>
                    <div id="chatHistory" class="response-area" style="min-height: 200px; display: block; background: #f8f9fa; color: #333;">
                        <div style="padding: 10px; color: #666;">对话将在这里显示...</div>
                    </div>
                </div>
                <div class="form-group">
                    <label>您的问题 *</label>
                    <textarea id="qaMessage" class="form-control" rows="3" placeholder="请输入您的问题...">人工智能的发展前景如何？</textarea>
                </div>
                <button class="btn" onclick="askQuestion()">🤖 提问</button>
                <button class="btn btn-secondary" onclick="clearChat()">🗑️ 清空对话</button>
                <div id="qaResponse" class="response-area" style="display: none;"></div>
            </div>

            <!-- 问答测试 -->
            <div class="function-card">
                <h3>🧪 问答API测试</h3>
                <p>测试问答API的连接状态和基本功能</p>
                <button class="btn" onclick="testQAAPI()">🧪 测试连接</button>
                <div id="qaTestResponse" class="response-area" style="display: none;"></div>
            </div>
        </div>

        <!-- 内容管理标签页（已隐藏） -->
        <div id="content" class="tab-content hidden">
            <div class="alert alert-info">
                <strong>💡 提示：</strong> 内容管理模块支持创建、编辑、删除、查询和导出多种格式的内容
            </div>

            <!-- 创建内容 -->
            <div class="function-card">
                <h3>📝 创建内容</h3>
                <div class="grid-2">
                    <div class="form-group">
                        <label>标题 *</label>
                        <input type="text" id="createTitle" class="form-control" placeholder="输入内容标题" value="我的第一篇文章">
                    </div>
                    <div class="form-group">
                        <label>内容类型 *</label>
                        <select id="createType" class="form-control">
                            <option value="article">文章</option>
                            <option value="note">笔记</option>
                            <option value="summary">摘要</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label>标签 (用逗号分隔)</label>
                    <input type="text" id="createTags" class="form-control" placeholder="例如：技术,AI,编程" value="技术,AI,编程">
                </div>
                <div class="form-group">
                    <label>内容正文 *</label>
                    <textarea id="createContent" class="form-control" rows="6" placeholder="输入内容正文...">这是一篇关于人工智能的文章。人工智能（AI）是计算机科学的一个分支，它企图了解智能的实质，并生产出一种新的能以人类智能相似的方式做出反应的智能机器。

该领域的研究包括机器人、语言识别、图像识别、自然语言处理和专家系统等。人工智能从诞生以来，理论和技术日益成熟，应用领域也不断扩大，可以设想，未来人工智能带来的科技产品，将会是人类智慧的"容器"。</textarea>
                </div>
                <button class="btn btn-success" onclick="createContent()">✨ 创建内容</button>
                <div id="createResponse" class="response-area" style="display: none;"></div>
            </div>

            <!-- 内容操作 -->
            <div class="function-card">
                <h3>🔧 内容操作</h3>
                <div class="grid-3">
                    <div class="form-group">
                        <label>内容ID</label>
                        <input type="text" id="contentId" class="form-control" placeholder="输入内容ID">
                    </div>
                    <div class="form-group">
                        <label>操作类型</label>
                        <select id="contentOperation" class="form-control">
                            <option value="get">获取内容</option>
                            <option value="update">更新内容</option>
                            <option value="delete">删除内容</option>
                            <option value="export">导出内容</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>导出格式 (仅导出时)</label>
                        <select id="exportFormat" class="form-control">
                            <option value="markdown">Markdown</option>
                            <option value="html">HTML</option>
                            <option value="txt">纯文本</option>
                        </select>
                    </div>
                </div>
                <div id="updateFields" style="display: none;">
                    <div class="grid-2">
                        <div class="form-group">
                            <label>新标题</label>
                            <input type="text" id="updateTitle" class="form-control" placeholder="输入新标题">
                        </div>
                        <div class="form-group">
                            <label>新标签</label>
                            <input type="text" id="updateTags" class="form-control" placeholder="输入新标签">
                        </div>
                    </div>
                    <div class="form-group">
                        <label>新内容</label>
                        <textarea id="updateContent" class="form-control" rows="4" placeholder="输入新内容..."></textarea>
                    </div>
                </div>
                <button class="btn" onclick="executeContentOperation()">🚀 执行操作</button>
                <div id="contentResponse" class="response-area" style="display: none;"></div>
            </div>

            <!-- 内容列表 -->
            <div class="function-card">
                <h3>📋 内容列表</h3>
                <div class="grid-3">
                    <div class="form-group">
                        <label>页码</label>
                        <input type="number" id="listPage" class="form-control" value="1" min="1">
                    </div>
                    <div class="form-group">
                        <label>每页数量</label>
                        <input type="number" id="listLimit" class="form-control" value="10" min="1" max="100">
                    </div>
                    <div class="form-group">
                        <label>内容类型过滤</label>
                        <select id="listType" class="form-control">
                            <option value="">全部类型</option>
                            <option value="article">文章</option>
                            <option value="note">笔记</option>
                            <option value="summary">摘要</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label>标签过滤</label>
                    <input type="text" id="listTag" class="form-control" placeholder="输入标签进行过滤">
                </div>
                <button class="btn" onclick="getContentList()">📋 获取列表</button>
                <div id="listResponse" class="response-area" style="display: none;"></div>
            </div>
        </div>

        <!-- 系统监控标签页 -->
        <div id="system" class="tab-content">
            <div class="alert alert-info">
                <strong>💡 提示：</strong> 系统监控模块提供健康检查、状态监控等系统级功能
            </div>

            <!-- 系统健康检查 -->
            <div class="function-card">
                <h3>💚 系统健康检查</h3>
                <p>检查系统整体运行状态和各个组件的健康状况</p>
                <button class="btn" onclick="checkSystemHealth()">💚 检查系统健康</button>
                <button class="btn" onclick="checkDatabaseHealth()">🗄️ 检查数据库健康</button>
                <div id="healthResponse" class="response-area" style="display: none;"></div>
            </div>

            <!-- API信息 -->
            <div class="function-card">
                <h3>📊 API信息</h3>
                <p>获取API版本、状态等基本信息</p>
                <button class="btn" onclick="getAPIInfo()">📊 获取API信息</button>
                <div id="apiInfoResponse" class="response-area" style="display: none;"></div>
            </div>

            <!-- 系统状态 -->
            <div class="function-card">
                <h3>📈 系统状态</h3>
                <p>实时监控系统运行状态和性能指标</p>
                <button class="btn" onclick="getSystemStatus()">📈 获取系统状态</button>
                <div id="statusResponse" class="response-area" style="display: none;"></div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentContentId = null;
        const API_BASE = '/api';
        
        // 注意：前端API设计已适配秘塔AI的扁平数据结构
        // 后端返回格式：{success: true/false, query: '', results: [], ...}
        // 而不是嵌套格式：{success: true/false, data: {...}}

        // 显示标签页
        function showTab(tabName) {
            // 隐藏所有标签页内容
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 移除所有标签页的active状态
            document.querySelectorAll('.nav-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 显示选中的标签页
            document.getElementById(tabName).classList.add('active');
            
            // 激活对应的导航标签
            event.target.classList.add('active');
        }

        // 显示响应
        function showResponse(elementId, data, isSuccess = true) {
            const element = document.getElementById(elementId);
            element.style.display = 'block';
            
            if (typeof data === 'object') {
                element.innerHTML = JSON.stringify(data, null, 2);
            } else {
                element.innerHTML = data;
            }
            
            element.className = `response-area ${isSuccess ? 'status-success' : 'status-error'}`;
        }

        // 显示加载状态
        function showLoading(elementId) {
            const element = document.getElementById(elementId);
            element.style.display = 'block';
            element.innerHTML = '<div class="loading"><div class="spinner"></div>正在处理请求...</div>';
        }

        // 通用API请求函数
        async function makeRequest(url, options = {}) {
            try {
                const response = await fetch(url, {
                    headers: {
                        'Content-Type': 'application/json',
                        ...options.headers
                    },
                    ...options
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                return await response.json();
            } catch (error) {
                throw new Error(`请求失败: ${error.message}`);
            }
        }

        // 切换分页输入框显示
        function togglePagingInputs() {
            const pagingType = document.querySelector('input[name="pagingType"]:checked').value;
            const pageGroup = document.getElementById('pageGroup');
            const sizeGroup = document.getElementById('sizeGroup');
            
            if (pagingType === 'page') {
                pageGroup.style.display = 'block';
                sizeGroup.style.display = 'none';
            } else {
                pageGroup.style.display = 'none';
                sizeGroup.style.display = 'block';
            }
        }

        // 智能搜索功能
        async function executeSearch() {
            const query = document.getElementById('searchQuery').value.trim();
            if (!query) {
                alert('请输入搜索关键词');
                return;
            }

            // 获取选中的搜索范围
            const selectedScopes = [];
            const scopeCheckboxes = document.querySelectorAll('#searchScope input[type="checkbox"]:checked');
            scopeCheckboxes.forEach(checkbox => {
                selectedScopes.push(checkbox.value);
            });
            
            if (selectedScopes.length === 0) {
                alert('请至少选择一个搜索范围');
                return;
            }

            showLoading('searchResponse');
            
            try {
                const data = {
                    q: query,
                    scope: selectedScopes.join(','),
                    includeSummary: document.getElementById('includeSummary').value === 'true'
                };

                // 根据用户选择的分页方式添加对应参数
                const pagingType = document.querySelector('input[name="pagingType"]:checked').value;
                if (pagingType === 'page') {
                    data.page = parseInt(document.getElementById('searchPage').value);
                } else {
                    data.size = parseInt(document.getElementById('searchSize').value);
                }

                const response = await makeRequest(`${API_BASE}/search/`, {
                    method: 'POST',
                    body: JSON.stringify(data)
                });

                // 适配扁平数据结构，检查是否有success字段
                const isSuccess = response.success !== false;
                showResponse('searchResponse', response, isSuccess);
            } catch (error) {
                showResponse('searchResponse', { error: error.message }, false);
            }
        }

        // 网页读取功能
        async function readWebpage() {
            const url = document.getElementById('readerUrl').value.trim();
            if (!url) {
                alert('请输入网页URL');
                return;
            }

            showLoading('readerResponse');
            
            try {
                const response = await makeRequest(`${API_BASE}/reader?url=${encodeURIComponent(url)}`);
                const isSuccess = response.success !== false;
                showReaderResponse('readerResponse', response, isSuccess);
            } catch (error) {
                showResponse('readerResponse', { error: error.message }, false);
            }
        }

        // 专门用于显示网页读取结果的函数
        function showReaderResponse(elementId, data, isSuccess = true) {
            const element = document.getElementById(elementId);
            element.style.display = 'block';
            // 仅使用专用的 reader-area 样式，避免绿色/红色背景影响可读性
            element.className = 'reader-area';
            
            if (!isSuccess || !data.success) {
                element.innerHTML = `<div style="color: #e74c3c; font-weight:600;">❌ 错误: ${data.error || '未知错误'}</div>`;
                return;
            }
            
            // 构建格式化的显示内容（高对比度 + 大字号）
            let html = '';
            html += `<div style="color:#27ae60; font-weight:700; margin-bottom:6px;">✅ 网页读取成功</div>`;
            html += `<div class="reader-meta"><strong>📄 标题:</strong> ${data.title || '无标题'}</div>`;
            html += `<div class="reader-meta"><strong>🔗 URL:</strong> <a href="${data.url || '#'}" target="_blank" style="color:#3498db; text-decoration:underline;">${data.url || '无URL'}</a></div>`;
            if (data.author) html += `<div class="reader-meta"><strong>👤 作者:</strong> ${data.author}</div>`;
            if (data.date) html += `<div class="reader-meta"><strong>📅 日期:</strong> ${data.date}</div>`;
            html += `<div class="reader-meta"><strong>⏰ 时间:</strong> ${data.timestamp}</div>`;
            
            if (data.markdown && data.markdown.trim()) {
                html += `<div class="reader-meta" style="margin-top:10px; color:#2c3e50; font-weight:600;">📝 内容（${data.markdown.length} 字符）</div>`;
                html += `<pre class="reader-pre">${data.markdown.replace(/</g, '&lt;').replace(/>/g, '&gt;')}</pre>`;
            } else {
                html += `<div style="color:#e67e22; margin-top:8px;">⚠️ 警告: 未获取到网页内容</div>`;
            }
            
            if (data.credits !== undefined && data.credits !== null) {
                html += `<div class="reader-meta" style="color:#6b7280;">💰 积分信息: ${data.credits}</div>`;
            }
            
            element.innerHTML = html;
        }

        async function testReaderAPI() {
            showLoading('readerTestResponse');
            
            try {
                const response = await makeRequest(`${API_BASE}/reader/test`);
                const isSuccess = response.success !== false;
                showResponse('readerTestResponse', response, isSuccess);
            } catch (error) {
                showResponse('readerTestResponse', { error: error.message }, false);
            }
        }

        // 对话历史存储
        let chatMessages = [];

        // 智能问答功能
        async function askQuestion() {
            const message = document.getElementById('qaMessage').value.trim();
            if (!message) {
                alert('请输入您的问题');
                return;
            }

            // 添加用户消息到对话历史
            chatMessages.push({
                role: 'user',
                content: message
            });

            updateChatHistory();
            showLoading('qaResponse');
            
            try {
                const data = {
                    messages: chatMessages,
                    scope: document.getElementById('qaScope').value,
                    model: document.getElementById('qaModel').value
                };

                const response = await makeRequest(`${API_BASE}/chat/completions`, {
                    method: 'POST',
                    body: JSON.stringify(data)
                });

                // 添加AI回复到对话历史
                if (response.choices && response.choices[0] && response.choices[0].message) {
                    chatMessages.push({
                        role: 'assistant',
                        content: response.choices[0].message.content
                    });
                    updateChatHistory();
                }

                const isSuccess = response.success !== false;
                showResponse('qaResponse', response, isSuccess);
                
                // 清空输入框
                document.getElementById('qaMessage').value = '';
            } catch (error) {
                showResponse('qaResponse', { error: error.message }, false);
            }
        }

        // 更新对话历史显示
        function updateChatHistory() {
            const chatHistoryDiv = document.getElementById('chatHistory');
            if (chatMessages.length === 0) {
                chatHistoryDiv.innerHTML = '<div style="padding: 10px; color: #666;">对话将在这里显示...</div>';
                return;
            }

            let historyHtml = '';
            chatMessages.forEach((msg, index) => {
                const isUser = msg.role === 'user';
                const bgColor = isUser ? '#e3f2fd' : '#f1f8e9';
                const icon = isUser ? '👤' : '🤖';
                const label = isUser ? '用户' : 'AI助手';
                
                historyHtml += `
                    <div style="margin: 10px 0; padding: 10px; background: ${bgColor}; border-radius: 8px; border-left: 4px solid ${isUser ? '#2196f3' : '#4caf50'};">
                        <div style="font-weight: bold; margin-bottom: 5px; color: #333;">
                            ${icon} ${label}
                        </div>
                        <div style="color: #555; white-space: pre-wrap;">${msg.content}</div>
                    </div>
                `;
            });
            
            chatHistoryDiv.innerHTML = historyHtml;
            chatHistoryDiv.scrollTop = chatHistoryDiv.scrollHeight;
        }

        // 清空对话
        function clearChat() {
            chatMessages = [];
            updateChatHistory();
            document.getElementById('qaResponse').style.display = 'none';
        }

        async function testQAAPI() {
            showLoading('qaTestResponse');
            
            try {
                const response = await makeRequest(`${API_BASE}/chat/test`);
                const isSuccess = response.success !== false;
                showResponse('qaTestResponse', response, isSuccess);
            } catch (error) {
                showResponse('qaTestResponse', { error: error.message }, false);
            }
        }

        async function getSuggestions() {
            const query = document.getElementById('suggestionQuery').value.trim();
            if (!query) {
                alert('请输入查询词');
                return;
            }

            showLoading('suggestionResponse');
            
            try {
                const limit = document.getElementById('suggestionLimit').value;
                const response = await makeRequest(`${API_BASE}/search/suggestions?q=${encodeURIComponent(query)}&limit=${limit}`);
                // 适配扁平数据结构
                const isSuccess = response.success !== false;
                showResponse('suggestionResponse', response, isSuccess);
            } catch (error) {
                showResponse('suggestionResponse', { error: error.message }, false);
            }
        }

        async function getSearchHistory() {
            const userId = document.getElementById('historyUserId').value.trim();
            if (!userId) {
                alert('请输入用户ID');
                return;
            }

            showLoading('historyResponse');
            
            try {
                const limit = document.getElementById('historyLimit').value;
                const response = await makeRequest(`${API_BASE}/search/history?user_id=${encodeURIComponent(userId)}&limit=${limit}`);
                // 适配扁平数据结构
                const isSuccess = response.success !== false;
                showResponse('historyResponse', response, isSuccess);
            } catch (error) {
                showResponse('historyResponse', { error: error.message }, false);
            }
        }

        async function clearSearchHistory() {
            const userId = document.getElementById('historyUserId').value.trim();
            if (!userId) {
                alert('请输入用户ID');
                return;
            }

            if (!confirm('确定要清除搜索历史吗？此操作不可恢复。')) {
                return;
            }

            showLoading('historyResponse');
            
            try {
                const response = await makeRequest(`${API_BASE}/search/history`, {
                    method: 'DELETE',
                    body: JSON.stringify({ user_id: userId })
                });
                // 适配扁平数据结构
                const isSuccess = response.success !== false;
                showResponse('historyResponse', response, isSuccess);
            } catch (error) {
                showResponse('historyResponse', { error: error.message }, false);
            }
        }

        async function testSearchAPI() {
            showLoading('testResponse');
            
            try {
                const response = await makeRequest(`${API_BASE}/search/test`);
                // 适配扁平数据结构
                const isSuccess = response.success !== false;
                showResponse('testResponse', response, isSuccess);
            } catch (error) {
                showResponse('testResponse', { error: error.message }, false);
            }
        }

        // 内容管理功能
        async function createContent() {
            const title = document.getElementById('createTitle').value.trim();
            const content = document.getElementById('createContent').value.trim();
            const type = document.getElementById('createType').value;
            const tags = document.getElementById('createTags').value.split(',').map(tag => tag.trim()).filter(tag => tag);

            if (!title || !content) {
                alert('标题和内容不能为空');
                return;
            }

            showLoading('createResponse');
            
            try {
                const data = { title, content, type, tags };
                const response = await makeRequest(`${API_BASE}/content/`, {
                    method: 'POST',
                    body: JSON.stringify(data)
                });

                // 适配扁平数据结构，检查是否有success字段
                const isSuccess = response.success !== false;
                if (isSuccess && response.id) {
                    currentContentId = response.id;
                    document.getElementById('contentId').value = currentContentId;
                }

                showResponse('createResponse', response, isSuccess);
            } catch (error) {
                showResponse('createResponse', { error: error.message }, false);
            }
        }

        async function executeContentOperation() {
            const operation = document.getElementById('contentOperation').value;
            const contentId = document.getElementById('contentId').value.trim();

            if (!contentId) {
                alert('请输入内容ID');
                return;
            }

            showLoading('contentResponse');
            
            try {
                let response;
                
                switch (operation) {
                    case 'get':
                        response = await makeRequest(`${API_BASE}/content/${contentId}`);
                        break;
                        
                    case 'update':
                        const updateData = {};
                        const updateTitle = document.getElementById('updateTitle').value.trim();
                        const updateContent = document.getElementById('updateContent').value.trim();
                        const updateTags = document.getElementById('updateTags').value.split(',').map(tag => tag.trim()).filter(tag => tag);
                        
                        if (updateTitle) updateData.title = updateTitle;
                        if (updateContent) updateData.content = updateContent;
                        if (updateTags.length > 0) updateData.tags = updateTags;
                        
                        if (Object.keys(updateData).length === 0) {
                            alert('请至少输入一个要更新的字段');
                            return;
                        }
                        
                        response = await makeRequest(`${API_BASE}/content/${contentId}`, {
                            method: 'PUT',
                            body: JSON.stringify(updateData)
                        });
                        break;
                        
                    case 'delete':
                        if (!confirm('确定要删除这个内容吗？此操作不可恢复。')) {
                            return;
                        }
                        response = await makeRequest(`${API_BASE}/content/${contentId}`, {
                            method: 'DELETE'
                        });
                        break;
                        
                    case 'export':
                        const format = document.getElementById('exportFormat').value;
                        window.open(`${API_BASE}/content/export/${contentId}?format=${format}`, '_blank');
                        showResponse('contentResponse', { message: '导出请求已发送，请查看新窗口' }, true);
                        return;
                }
                
                // 适配扁平数据结构
                const isSuccess = response.success !== false;
                showResponse('contentResponse', response, isSuccess);
            } catch (error) {
                showResponse('contentResponse', { error: error.message }, false);
            }
        }

        async function getContentList() {
            showLoading('listResponse');
            
            try {
                const page = document.getElementById('listPage').value;
                const limit = document.getElementById('listLimit').value;
                const type = document.getElementById('listType').value;
                const tag = document.getElementById('listTag').value.trim();
                
                let url = `${API_BASE}/content/list?page=${page}&limit=${limit}`;
                if (type) url += `&type=${type}`;
                if (tag) url += `&tag=${encodeURIComponent(tag)}`;
                
                const response = await makeRequest(url);
                // 适配扁平数据结构
                const isSuccess = response.success !== false;
                showResponse('listResponse', response, isSuccess);
            } catch (error) {
                showResponse('listResponse', { error: error.message }, false);
            }
        }

        // 系统监控功能
        async function checkSystemHealth() {
            showLoading('healthResponse');
            
            try {
                const response = await makeRequest('/health');
                showResponse('healthResponse', response, true);
            } catch (error) {
                showResponse('healthResponse', { error: error.message }, false);
            }
        }

        async function checkDatabaseHealth() {
            showLoading('healthResponse');
            
            try {
                const response = await makeRequest('/health/database');
                showResponse('healthResponse', response, true);
            } catch (error) {
                showResponse('healthResponse', { error: error.message }, false);
            }
        }

        async function getAPIInfo() {
            showLoading('apiInfoResponse');
            
            try {
                const response = await makeRequest(`${API_BASE}/health`);
                showResponse('apiInfoResponse', response, true);
            } catch (error) {
                showResponse('apiInfoResponse', { error: error.message }, false);
            }
        }

        async function getSystemStatus() {
            showLoading('statusResponse');
            
            try {
                const response = await makeRequest(`${API_BASE}/health`);
                showResponse('statusResponse', response, true);
            } catch (error) {
                showResponse('statusResponse', { error: error.message }, false);
            }
        }

        // 监听内容操作类型变化
        document.getElementById('contentOperation').addEventListener('change', function() {
            const updateFields = document.getElementById('updateFields');
            if (this.value === 'update') {
                updateFields.style.display = 'block';
            } else {
                updateFields.style.display = 'none';
            }
        });

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('MetasoCreator 功能演示页面加载完成');
            console.log('请确保后端服务正在运行在 http://localhost:5000');
            const contentTab = document.querySelector('.nav-tab[onclick="showTab(\'content\')"]');
            if (contentTab) contentTab.classList.add('hidden');
            const contentPage = document.getElementById('content');
            if (contentPage) contentPage.classList.add('hidden');
        });
    </script>
</body>
</html>